/*
 *                  BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 * 
 * Created on Feb 6, 2006
 * @author Jonathan Warren
 *
 */
package org.biojava.services.das.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.biojava.dasobert.das.Capabilities;
import org.biojava.dasobert.das.DasSpec;
import org.biojava.dasobert.das2.io.DASRegistryCoordinatesReaderXML;
import org.biojava.dasobert.dasregistry.DasCoordinateSystem;
import org.biojava.dasobert.dasregistry.DasSource;
import org.biojava.dasobert.dasregistry.DasSourceComparator;
import org.biojava.dasobert.dasregistry.DasSourceFilter;
import org.biojava.services.das.dao.DasServer;
import org.biojava.services.das.dao.ServerManager;
import org.biojava.services.das.dao.OrganismBean;
import org.biojava.services.das.registry.DASQueryStringTranslator;
import org.biojava.services.das.registry.DasRegistrySql;
import org.biojava.services.das.registry.RegistryDirectoryInfo;
import org.biojava.services.das2.Das1SourceDbProvider;
import org.biojava.services.das2.DasSourceProvider; //import org.biojava.servlets.dazzle.DASQueryStringTranslator;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import uk.ac.sanger.www.WTSISearchService.GetResultsFromSanger;

import dasregistry.registryBean;
import dasregistry.utils.RegistryCache;
import dasregistry.utils.RowsFilter;
import dasregistry.utils.SingletonRegistryCache;

public class Das2RegistryServlet extends HttpServlet {

	public static final long serialVersionUID = 237894238679342789l;

	public static final String VERSION = "2.2.x";

	private static String XSL_FILE = "das.xsl";
	private static String DAS2_SOURCES = "das2.sources";
	private boolean gzipEncoding = true;

	public static final String DASNS = "http://biodas.org/documents/das2";
	//DasSourceProvider das1provider;
	SingletonRegistryCache cache;
	DasSourceProvider das2provider;
	//RegistryCache cache;
	DasRegistrySql registry=null;
	
	public Das2RegistryServlet() {
		super();
System.out.println("init das2registryservlet");
	}

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		
		BeanFactory ctx=(new ClassPathXmlApplicationContext("SpringDAO.xml"));
		registry=(DasRegistrySql)ctx.getBean("registryBean");// get the last modified
														// date from the
														// registry not the
														// servlet!

		cache =(SingletonRegistryCache)ctx.getBean("registryCache");
	}

	public void destroy() {
		cache = null;
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// RegistryDirectoryInfo
		// info=RegistryDirectoryInfo.getRegistryDirectoryInfo();
		// String directory=getServletContext().getRealPath("/");
		// info.setIndexDirectory(directory);
		req = new DASQueryStringTranslator(req);
		
		
		resp = gzipEncoding(req, resp);

		resp.setHeader("Access-Control-Allow-Origin", "*");
		StringTokenizer toke = getTokensFromQueryString(req);
		if (!toke.hasMoreTokens()) {
			welcomePage(req, resp);
			return;
		}
		String command = toke.nextToken();

		List<String> nameComponents = new ArrayList<String>();

		// System.out.println("got command " + command);

		if (command.equalsIgnoreCase("das.xsl")) {
			// return the xsl file
			showXSLFile(resp);
			return;
		}

		String prevCommand = "";
		while (toke.hasMoreTokens()) {
			nameComponents.add(command);
			prevCommand = command;
			command = toke.nextToken();
			// System.out.println("got command " + command);
			if (command.equalsIgnoreCase("das.xsl")) {
				// return the xsl file
				showXSLFile(resp);
				return;
			}
		}

		// if ( prevCommand.equalsIgnoreCase("css")){
		// sendStylesheet(req,resp,command);
		// return;
		// }

		int dasversion = getDasVersionFromURI(req.getRequestURI());

		boolean responded = false;// need to set this to true otherwise comes
									// out as text/html as displays welcome page
									// on end?
		try {
			System.out.println("got command >" + command + "<");

			if (prevCommand.equalsIgnoreCase("css")) {
				// a stylesheet was requested
				sendStylesheet(req, resp, command);
				responded = true;
			} else if (command.startsWith("DS_")
					|| (toke.countTokens() == 0 && !command.equals("servers")
							&& !command.equals("sources")
							&& !command.equals("coordinatesystem")
							&& !command.equals("organism")
							&& !command.equals("lastModified")
							&& !command.equals("knownCapabilities") && !command
							.startsWith("CS_")&&!command
							.startsWith("refreshCache"))) {
				// System.out.println("got das single source command="+command);
				if (dasversion == 1) {
					displaySingleDas1Source(req, resp, command);
					responded = true;
				}
				if (dasversion == 2) {
					displaySingleDas2Source(req, resp, command);
					responded = true;
				}

				// beyond this point we need to account for search option and
				// filter by searching first
			} else if (command.equals("sources")) {

				// get all DAS sources with label ...

				displayDas1Sources(req, resp);
				responded = true;

			} else if (command.equals("refreshCache")) {

				// get all DAS sources with label ...

				refreshCache(req, resp);
				responded = true;

			} else if (command.equals("organism")) {
				// provide a new "organisms" command
				// System.out.println("requested " + command);
				sendOrganism(req, resp);
				responded = true;

			} else if (command.equals("coordinatesystem")) {
				// provide a new "cpprdoamtesystem" command
				// System.out.println("requested " + command);
				if (req.getMethod().equals("GET")) {
					sendCoordinateSystem(req, resp);
				} else {
					createCoordinateSystem(req, resp);
				}
				responded = true;

			} else if (command.equals("lastModified")) {
				sendLastModified(req, resp);
				responded = true;
			} else if (command.equals("knownCapabilities")) {
				displayKnownCapabilties(resp);
				responded = true;
			} else if (command.equals("servers")) {
				this.writeServers(req, resp);
				responded = true;
			} else if (command.startsWith("CS_")) {
				sendSingleCoordinateSystem(req, resp, command);
				responded = true;
			} else {

				// System.out.println(nameComponents + " " +
				// nameComponents.size());
				if (nameComponents.size() == 1) {
					String s1 = nameComponents.get(0);
					// System.out.println("name component 1 " + s1 + " " +
					// dasversion);
					if (s1.equals("sources")) {
						// System.out.println("requesting source description for single DAS source "
						// + command);
						if (dasversion == 1) {
							displaySingleDas1Source(req, resp, command);
							responded = true;
						}
						if (dasversion == 2) {
							displaySingleDas2Source(req, resp, command);
							responded = true;
						}

					}
				}
			}
			if (!responded) {
				welcomePage(req, resp);
			}
		} catch (Exception e) {
			// sendError()
			e.printStackTrace();
		}

		// resp.getOutputStream().flush();

	}

	private void refreshCache(HttpServletRequest req, HttpServletResponse resp) {
		this.cache.refreshAll();
		
	}

	private void writeServers(HttpServletRequest req, HttpServletResponse resp) {
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Content-Type",ServletResponseWriter.XML_CONTENT_TYPE );
		resp.setHeader("X-DAS-Status", ServletResponseWriter.XDASOK);
		DasServerResponseWriter serverWriter = new DasServerResponseWriter();
		// System.out.println("writing response:");
		List<DasServer> servers = this.getDasServers(req);

		RowsFilter rows = new RowsFilter();
		servers = rows.filterByRows(servers, req);
		try {
			serverWriter.writeResponse(resp, servers, rows.getTotal(), rows
					.getStart(), rows.getStop());
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private StringTokenizer getTokensFromQueryString(HttpServletRequest req) {
		String queryString = req.getQueryString();

		//System.out.println("queryStirng=" + queryString);
		String cmdPath = req.getPathInfo();
		if (cmdPath == null) {
			cmdPath = "";
		}
		//System.out.println("commandPath " + cmdPath);

		StringTokenizer toke = new StringTokenizer(cmdPath, "/");
		return toke;
	}

	private HttpServletResponse gzipEncoding(HttpServletRequest req,
			HttpServletResponse resp) {
		String encodingStr = req.getHeader("Accept-Encoding");
		if (encodingStr != null && gzipEncoding) {
			if (encodingStr.indexOf("gzip") != -1) {
				resp = new HttpServletResponseWrapper(resp) {
					GZIPOutputStream gzipOut = null;

					public PrintWriter getWriter() throws IOException {
						gzipOut = new GZIPOutputStream(getResponse()
								.getOutputStream());
						return new PrintWriter(gzipOut) {
							// we return a subclassed PrintWriter which finishes
							// GZIPOutputStream when close is called
							public void close() {
								super.close();
								try {
									gzipOut.finish();
								} catch (IOException ie) {
									System.err
											.println("Unexpected IOException when closing GZIPOutputStream");
								}
							}
						};
					}
				};
				resp.setHeader("Content-Encoding", "gzip");
			}
		}
		return resp;
	}

	private void sendOrganism(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {
		String keywords = req.getParameter("keywords");
		if (keywords != null && keywords != "") {
			// get ids from sanger

			// OrganismBean[] orgs = das1provider.getOrganisms();
			// ServletResponseWriter writer = new ServletResponseWriter();
			// writer.writeOrganismResponse(resp,orgs);
		} else {
			try {
				PrintWriter out = resp.getWriter();

				out
						.append("please specify a keyword parameter for filtering the results otherwise there are 400,000+ organisms that we cannot return");
				out.close();
			} catch (IOException e) {

				e.printStackTrace();
			}
		}

	}

	private void sendLastModified(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException {
		RegistryServletResponseWriter writer = new RegistryServletResponseWriter();
		writer.writeLastModified(resp);
	}

	private void sendCoordinateSystem(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException {
		String keywords = req.getParameter("keywords");
		
		List<DasCoordinateSystem> dcs = cache.getCoordinateSystems();
		List<DasCoordinateSystem> coordsToWrite = new ArrayList<DasCoordinateSystem>();
		// filter by the searh if keywords have been specified using sanger
		// search results
		if (keywords != null && keywords != "") {
			GetResultsFromSanger sanger = new GetResultsFromSanger();
			List<String> ids = sanger.getCoordinatesForKeyWords(keywords);
			for (DasCoordinateSystem coord : dcs) {
				String coordId = coord.getUniqueId();
				// System.out.println(coordId);
				if (ids.contains(coordId))
					coordsToWrite.add(coord);
			}
			// System.out.println("sourcesToWrite size=" +
			// coordsToWrite.size());
		} else {
			// if no keywords just copy to list to return all coords
			coordsToWrite = dcs;
		}
		RowsFilter rows = new RowsFilter();
		coordsToWrite = rows.filterByRows(coordsToWrite, req);
		ServletResponseWriter writer = new ServletResponseWriter();
		writer.writeCoordinateSystemResponse(resp, coordsToWrite, rows
				.getStart(), rows.getStop(), rows.getTotal());

	}

	private void createCoordinateSystem(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException {

		// The body content of the PUT/POST request is coordinate system XML,
		// except without a URI (which we are about to assign...

		try {

			DASRegistryCoordinatesReaderXML reader = new DASRegistryCoordinatesReaderXML();

			List<DasCoordinateSystem> dcs = reader.readRegistryCoordinates(req
					.getInputStream());
			Exception error = reader.getLoggedException();
			if (error != null) {
				throw error;
			};
			
			List<DasCoordinateSystem> createdCoords=null;
			try {
				createdCoords = registry.createCoordinateSystems(dcs);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ServletResponseWriter writer = new ServletResponseWriter();
			writer.writeCoordinateSystemResponse(resp, createdCoords, 0, 0, 0);
			registry.pingLastModified();

		} catch (Exception e) {
			e.printStackTrace();
			try {
				resp.setHeader("X-DAS-Status", "402");
				resp.sendError(resp.SC_BAD_REQUEST, e.getMessage());
			} catch (IOException e2) {
				e.printStackTrace();
			}
		}

	}

	private void sendStylesheet(HttpServletRequest req,
			HttpServletResponse resp, String command) throws IOException,
			ServletException {

		// System.out.println("getting css " + command);

		String cssPath = "css/" + command;
		InputStream is = getClass().getClassLoader().getResourceAsStream(
				cssPath);

		if (is == null)
			throw new ServletException("No such css: " + command);

		PrintWriter pw = resp.getWriter();

		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line;
		while ((line = br.readLine()) != null) {
			// System.out.println(line);
			pw.println(line);
		}

		pw.close();
		pw.flush();

	}

	private void showXSLFile(HttpServletResponse resp) throws IOException {
		
		PrintWriter pw = resp.getWriter();
		InputStream is = getServletContext().getResourceAsStream(XSL_FILE);
		if (is != null) {
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line;
			while ((line = br.readLine()) != null) {
				// System.out.println(line);
				pw.println(line);
			}
		}
		pw.close();
		pw.flush();
	}

	private int getDasVersionFromURI(String uri) {
		int version = -1;
		String[] spl = uri.split("/");
		if (spl.length >= 2) {
			for (int i = 0; i < spl.length; i++) {
				String dasString = spl[i];
				System.out.println("|"+dasString+"|");
				if (dasString.equals("das"))return 1;
				if (dasString.equals("das1.5"))return 15;
				if (dasString.equals("das1.6")){
					return 16;
				}
				else if (dasString.equals("das1"))return 1;
				else if (dasString.equals("das2"))return 2;
			}
		}
		return version;
	}

	private void displaySingleDas2Source(HttpServletRequest req,
			HttpServletResponse resp, String dasSourceId)
			throws ServletException, IOException {
	}

	private void displaySingleDas1Source(HttpServletRequest req,
			HttpServletResponse resp, String dasSourceId)
			throws ServletException, IOException {
		boolean displayTimes=false;
		String times=req.getParameter("times");
		if(times!=null){
			if(times.equals("true"))displayTimes=true;
		}
		DasSource source =cache.getSingleDasSource(dasSourceId);
		List<DasSource> sources = new ArrayList<DasSource>();
		sources.add(source);
		ServletResponseWriter writer = new RegistryServletResponseWriter();
		writer.writeResponse(resp, sources, 0, 0, 0, displayTimes);
	}

	private void displayDas2Sources(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {

		System.out.println("printing DAS2 sources");

		// DasSource[] sources = das2provider.getDasSources();

		// ServletResponseWriter writer = new ServletResponseWriter();
		// writer.writeResponse(resp,sources);
		resp.setContentType(ServletResponseWriter.XML_CONTENT_TYPE);
		PrintWriter pw = resp.getWriter();
		InputStream is = getServletContext().getResourceAsStream(DAS2_SOURCES);
		if (is != null) {
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line;
			while ((line = br.readLine()) != null) {
				// System.out.println(line);
				pw.println(line);
			}
		}
		pw.close();

	}

	private void displayDas1Sources(HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		boolean displayTimes=false;
		String times=req.getParameter("times");
		if(times!=null){
			if(times.equals("true"))displayTimes=true;
		}
		String label = req.getParameter("label");
		String labels=req.getParameter("labels");
		if(labels!=null && labels!=""){
			label=labels;
		}
		String coordinateId=req.getParameter("coordinateid");
		String organism = req.getParameter("organism");
		String authority = req.getParameter("authority");
		String csName=req.getParameter("CSName");
		String version = req.getParameter("version");// version of the coordinate system
		if(csName!=null && csName!=""){
			authority=csName;
			if(authority.contains("_")){
				version=authority.substring(authority.indexOf("_")+1);
				authority=authority.substring(0,authority.indexOf("_"));
			}
		}
		String capability = req.getParameter("capability");
		System.out.println("capability in server="+capability);
		String capabilities=req.getParameter("capabilities");
		//want this to work with the user interface which uses different parameter
		if(capabilities!=null&& capabilities!=""){
			capability=capabilities;
		}
		System.out.println("capabilities="+capabilities);
		String type = req.getParameter("type");// type in coordinate
		// system e.g.
		// chromosome
		String csType=req.getParameter("CSTypes");
		if(csType!=null&& csType!=""){
			type=csType;
		}
		
		String rows=req.getParameter("rows");
		System.out.println("rows="+rows);
		// coordinate
		// system
		String keywords = req.getParameter("keywords");
		String typeskeywords = req.getParameter("typeskeywords");

		int dasspec = getDasVersionFromURI(req.getRequestURI());
		
		DasSpec spec = DasSpec.SPEC1_53E;// default
		if (dasspec == 1) {
			spec = null;
		}
		if (dasspec == 15) {
			spec = DasSpec.SPEC1_53E;
		}
		if (dasspec == 16) {
			spec = DasSpec.SPEC1_6E;
		}
		//override the url spec if a spec parameter has been specified
		if(req.getParameter("spec")!=null){
			String tempSpec=req.getParameter("spec");
		
			if(tempSpec.equals("any")){spec=null;
			
			}else{
			spec=DasSpec.convertToRegistrySpecification(req.getParameter("spec"));
			}
		}

		List<DasSource> sources = null;
		// cache all the sources and we can filter them if necessary
		String serverUrl = req.getParameter("serverUrl");
		if (serverUrl != null) {
			if (!serverUrl.endsWith("/"))
				serverUrl += "/";
			sources = this.getDas1SourcesForServerUrl(serverUrl);
		} else {
			sources = this.getDas1Sources(req);
		}

		List<DasSource> sourcesToWrite = new ArrayList<DasSource>();
		// filter by the searh if keywords have been specified using sanger
		// search results
		if (keywords != null && keywords != "") {
			GetResultsFromSanger sanger = new GetResultsFromSanger();
			List<String> ids = sanger.getSourcesForKeywordsSearch(keywords);
			for (DasSource source : sources) {
				String sourceId = source.getId();
				// System.out.println(sourceId);
				if (ids.contains(sourceId))
					sourcesToWrite.add(source);
			}
			
		} else if (typeskeywords != null && typeskeywords != "") {
			GetResultsFromSanger sanger = new GetResultsFromSanger();
			List<String> ids = sanger
					.getSourcesWithTypesLikeKeywordsSearch(typeskeywords);
			for (DasSource source : sources) {
				String sourceId = source.getId();
				// System.out.println(sourceId);
				if (ids.contains(sourceId))
					sourcesToWrite.add(source);
			}
			
		} else {
			sourcesToWrite = sources;
		}
		// filter by other properities if specified
		if(coordinateId!=null && coordinateId.equals("any"))coordinateId="";
		if(label!=null && label.equals("any"))label="";
		if(organism!=null && organism.equals("any"))organism="";
		if(authority!=null && authority.equals("any"))authority="";
		if(capability!=null && capability.equals("any"))capability="";
		if(type!=null && type.equals("any"))type="";
		System.out.println("got #sources " + sourcesToWrite.size()
				+ " filtering by label " + label + " org " + organism
				+ " authority " + authority + " capability " + capability
				+ " type " + type +" spec "+spec + " version "+version);

		DasSourceFilter filter = new DasSourceFilter();

		List<DasSource> filteredSources = filter.filterBy(sourcesToWrite,
				label, organism, authority, capability, type, spec, version, coordinateId);
		// System.out.println("got #source after filter: " + sources.length);
		
		//source for determining if we need to sort and sorting
		
		String sort=req.getParameter("sort");
		String reverse=req.getParameter("reverse");
		if (sort != null) {
			//sortstring = "&sort=" + sort;
			//sort das sources!
			if (reverse != null) {
				System.out.println("sorted reverse by " + sort);
				//notReverseString += "&reverse=true";

			} else {
				
				//reverseString += "&reverse=true";
				//System.out.println("reversestring="+reverseString);
			}

			System.out.println("sorted , reverse:" + reverse);

			Comparator dsc = DasSourceComparator.fromString(sort);
			java.util.Collections.sort(filteredSources, dsc);
			if (reverse != null) {
				// reverse order
				//java.util.List slist = java.util.Arrays.asList(s);
				System.out.println("reverse not null:" + reverse);
				java.util.Collections.reverse(filteredSources);
				
			}
		}

		writeDas1Sources(resp, req, filteredSources, displayTimes);

	}

	private void writeDas1Sources(HttpServletResponse resp,
			HttpServletRequest req, List<DasSource> filteredSources, boolean times)
			throws ServletException, IOException {

		RowsFilter rows = new RowsFilter();
		filteredSources = rows.filterByRows(filteredSources, req);
		ServletResponseWriter writer = new RegistryServletResponseWriter();
		// System.out.println("writing response:");
		writer.writeResponse(resp, filteredSources, rows.getTotal(), rows
				.getStart(), rows.getStop(), times);
	}

	private void displayKnownCapabilties(HttpServletResponse resp) {

		ServletResponseWriter writer = new RegistryServletResponseWriter();
		writer.writeKnownCapabilities(resp, this
				.getRegistryKnownCapaibilities());
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("got a post");
		doGet(req, resp);
	}

	private void welcomePage(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();
		pw.println("<html>");
		pw.println("<head>");
		pw.println("<title>DAS Registry Server information</title>");
		pw.println("</head>");
		pw.println("<body>");
		pw.println("<h1>DAS Registry Version" + VERSION + "</h1>");
		pw
				.println("you might want to do a <a href=\"http://www.dasregistry.org/das1/sources\">sources</a> request");
		pw.println("</body>");
		pw.println("</html>");
		pw.close();
		pw.flush();
	}

	// public long getLastModified(HttpServletRequest arg0) {
	// System.out.println("requested last modified ");
	// BeanFactory ctx=(new ClassPathXmlApplicationContext("SpringDAO.xml"));
		//DasRegistrySql registry=(DasRegistrySql)ctx.getBean("registryBean");
	// Date d = registry.getlastModified();
	//			
	// System.out.println(d);
	// return d.getTime();
	//	
	// }

	public List<DasSource> getDas1Sources(HttpServletRequest request) {
		List<DasSource> sources = cache.getDas1Sources();
		return sources;
	}

	public List<DasSource> getDas1SourcesForServerUrl(String serverUrl) {
		
		List<DasSource> sources = registry.getDasSourcesForServerURL(serverUrl);
		return sources;
	}

	public List<DasServer> getDasServers(HttpServletRequest request) {

		
		Date d = registry.getlastModified();
		Long lastModified = d.getTime();
		// List<DasSource> sources = cache.getDas1Sources(das1provider,
		// lastModified);
		List<DasServer> servers = null;
		try {
			servers = registry.listServers();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return servers;
	}

	public Capabilities[] getRegistryKnownCapaibilities() {
		return Capabilities.values();
	}

	private void sendSingleCoordinateSystem(HttpServletRequest req,
			HttpServletResponse resp, String name) {
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Content-Type", ServletResponseWriter.XML_CONTENT_TYPE);
		resp.setHeader("X-DAS-Status", ServletResponseWriter.XDASOK);
		List<DasCoordinateSystem> dcs = cache.getCoordinateSystems();
		List<DasCoordinateSystem> coordsToWrite = new ArrayList<DasCoordinateSystem>();

		for (DasCoordinateSystem coord : dcs) {

			if (coord.getUniqueId().equalsIgnoreCase(name)) {
				// / we found it!
				coordsToWrite.add(coord);
			}
		}

		ServletResponseWriter writer = new ServletResponseWriter();
		writer.writeCoordinateSystemResponse(resp, coordsToWrite, 0, 0, 0);
	}

}
